<?php

namespace app\controller\adminapi\addonAuth;

use think\App;
use app\common\model\addon\Addons;
use app\common\services\table\DataForm;
use app\common\services\table\DataTable;
use hiduoke\controller\AdminController;
use hiduoke\services\FormBuilder as Form;
use app\common\model\addonAuth\AddonGroup as AddonGroupModel;
use Throwable;

class AddonGroup extends AdminController
{
    /**
     * @var AddonGroupModel
     */
    public $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new AddonGroupModel();
    }

    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->append(['explain'])
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    /**
     * 用户列表 TODO 待完善 是否为默认 选择应用 默认图
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $column = $DataTable
            ->setFilterFields(['type'])
            ->setField('default', ['render' => 'switch'])
            ->setField('addons', ['slotName' => 'addons_slot', 'width' => '800px', 'label' => '应用列表'])
            ->operation()->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }


    /**
     * 获取表单
     * @param $id
     * @return \think\response\Json
     */
    public function form()
    {
        $dataForm = new DataForm($this->model);
        $addonsExplain = (new Addons())->getAddonsByFormDataAddons($dataForm->row['addons']);
        $form = $dataForm
            ->setFilterFields(['type'])
            ->setField('default', ['render' => 'switch'])
            ->setRule(
                'addons',
                Form::dkAddonSelect('addons', '应用及权限', $dataForm->row['addons'] ?? [])
                    ->appendToBody()
                    ->addonsExplain($addonsExplain)
                    ->required()
            )
            ->config(['width' => '1200px'])
            ->create();
        return $this->success('', $form);
    }



    /**
     * 新增&修改
     * @return \think\response\Json
     */
    public function save()
    {
        $id = input('id', 0);
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        if (isset($formData['default']) && $formData['default'] == '1') {
            $this->model->where('default', 1)->update(['default' => 0]);
        }
        $row->save($formData);
        return $this->success('保存成功');
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error('未找到记录');
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            //            var_dump($data);exit();
            if (!$data) {
                $this->error("参数不能为空", ['']);
            }

            $data = $this->excludeFields($data);
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if (isset($data['default']) &&  $data['default'] == '1') {
                    // 设置默认项
                    $this->model->where('default', 1)->update(['default' => 0]);
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('更新成功');
            } else {
                $this->error('未更新任何行');
            }
        }

        return $this->success('更新成功', [
            'row' => $row
        ]);
    }

    /**
     * 设置应用到默认组
     * @param string $addon_name
     * @return \think\response\Json
     */
    public function addDefaultAddon($addon_name = null)
    {
        if (!$addon_name) {
            $addon_name = $this->request->param('addon_name', '');
        }

        if (empty($addon_name)) {
            return $this->error('应用名称不能为空');
        }

        try {
            // 获取默认应用组
            $defaultGroup = $this->model->where('default', 1)->find();

            if (!$defaultGroup) {
                // 如果没有默认组，创建一个
                $defaultGroup = $this->model->create([
                    'name' => '默认应用组',
                    'addons' => [$addon_name => ['all']],
                    'type' => 'default',
                    'default' => 1
                ]);
                return $this->success('已创建默认应用组并添加应用');
            }

            // 获取当前应用组的应用列表
            $currentAddons = $defaultGroup->addons ?: [];

            // 检查应用是否已存在
            if (isset($currentAddons[$addon_name])) {
                return $this->success('应用已在默认组中');
            }

            // 添加新应用到默认组
            $currentAddons[$addon_name] = ['all'];
            $defaultGroup->addons = $currentAddons;
            $defaultGroup->save();

            return $this->success('已添加应用到默认组');
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }
}
